#include "TaskExecutor.h"
#include "ThreadPool.h"

using namespace std;
using namespace threadpool;

ThreadStatus TaskExecutor::defaultBeforeExecute(const std::shared_ptr<Task> &task, ThreadPool *pool) {
    if (task->getType() == "TimedTask") {
        auto *timed_task = dynamic_cast<TimedTask *>(task.get());
        this_thread::sleep_for(timed_task->getDelay());
    } else if (task->getType() == "PeriodicTask") {
        auto *periodic_task = dynamic_cast<PeriodicTask *>(task.get());
        this_thread::sleep_for(periodic_task->getPeriod());
    }
    return customBeforeExecute(task, pool);
}

ThreadStatus TaskExecutor::defaultAfterExecute(const std::shared_ptr<Task> &task, ThreadPool *pool) {
    if (task->getType() == "SuicideTask") {
        pool->submitPriorityTask(0, [&](const thread::id &id) {
            size_t index = 0;
            lock_guard<mutex> lock(pool->mutex_);
            for (; index < pool->workers_.size(); ++index) {
                if (pool->workers_[index].get_id() == id) {
                    pool->workers_[index].join();
                }
            }
            pool->workers_.erase(pool->workers_.begin() + index);
        }, this_thread::get_id());
        return ThreadStatus::ThreadExit;
    } else if (task->getType() == "PeriodicTask") {
        pool->queue_.push(task);
    }
    ThreadStatus status = customAfterExecute(task, pool);
    return status;
}
